package com.epalmpay.controller.apiShopApp;

import com.epalmpay.commom.BaseController;
import com.epalmpay.dto.system.*;
import com.epalmpay.entity.Shop;
import com.epalmpay.entity.Userbase;
import com.epalmpay.enumdef.BizEnum;
import com.epalmpay.exception.ApplicationException;
import com.epalmpay.service.app.IAppUserService;
import com.epalmpay.service.management.IUserService;
import com.epalmpay.service.shop.IShopService;
import com.epalmpay.service.weixin.ITokenService;
import com.epalmpay.status.Rescode;
import com.epalmpay.util.*;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * Created by Administrator on 2018/2/26.
 */
@Controller
@RequestMapping(value="/app/user")
public class AppUserController extends BaseController {

    @Resource
    private IUserService userService;

    @Resource
    private IShopService shopService;

    @Resource
    private ITokenService tokenService;

    @Resource
    private IAppUserService appUserService;




    /**
     * App用户登陆
     *
     */
    @RequestMapping(value="/userLoginApp")
    @ResponseBody
    public LoginInOutDTO userLoginApp(LoginInInDTO loginIn){
        LoginInOutDTO loginInOut=new LoginInOutDTO();
        try {
            Userbase user=new Userbase();
            user.setUsername(loginIn.getUsername());
            user.setPassword(new SimpleHash("SHA-1", loginIn.getUsername(), loginIn.getPassword()).toString());
            List<Userbase> userlist = userService.getUserByNameAndPwd(user);
            //对象反射复制
            if(userlist.size()==1){
                Userbase users=userlist.get(0);
                if(users.getStatus()==1){
                    UserInDTO userIn = new UserInDTO();
                    userIn.setUserType(users.getUserType());
                    userIn.setUserId(users.getId());
                    UserOutDTO  userOutDTO = userService.shopOrAgent(userIn);
                    loginInOut.setShopid(userOutDTO.getShopId());
                    PropertyCopyUtil.copyPropertiesExclude(users,loginInOut);
                    loginInOut.setGroupName(users.getGroup().getMerchantName());
                    loginInOut.setToken(tokenService.getTokenInfo(userOutDTO.getShopId().toString()).getValue());

                    loginInOut.setErrorCode(Rescode.SUCCESS, "登录成功");
                }else{
                    loginInOut.setErrorCode(Rescode.LOCKING_ERROR, "账户被锁定,请与管理员联系");
                }
            }else{
                loginInOut.setErrorCode(Rescode.PASSWORD_ERROR, "密码错误");
            }
        } catch (Exception e) {
            loginInOut.setErrorCode("-1", "处理出现异常");
            e.printStackTrace();
        }
        return loginInOut;
    }

    /**
     *
     * 获取门店信息
     *
     */
    @RequestMapping(value="/getUserInfoById")
    @ResponseBody
    public ShopOutDTO getUserInfoById(ShopInDTO shopIn){
        ShopOutDTO shopOutDTO = new ShopOutDTO();
        try {
            Shop shop = shopService.getShopIdByUserId(shopIn.getUserId());
            shopIn.setId(shop.getId());
            shopIn.setGroupId(shopIn.getGroupId());
            shopOutDTO = shopService.selectShopInfo(shopIn);
            shopOutDTO.setErrorCode(Rescode.SUCCESS, "查询成功");
        } catch (Exception e) {
            shopOutDTO.setErrorCode("-1", "处理出现异常");
            e.printStackTrace();
        }
        return shopOutDTO;
    }

    /**
     * 修改门店经营信息
     * @param shopId
     * @param shopName
     * @param shopPhone
     * @param wordTime
     * @param icon
     * @param provinceCityDistrict
     * @param address
     * @param memo
     * @return
     */
    @RequestMapping(value="/updateShopBusiness")
    @ResponseBody
    public Response updateShopBusiness(String shopId,String shopName,String shopPhone,String wordTime,String icon,String provinceCityDistrict
            ,String address,String memo){
        logBefore(logger, "修改门店经营信息");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("商户编号", shopId);
        resultMap.put("门店名称", shopName);
        resultMap.put("门店电话", shopPhone);
        resultMap.put("门店工作时间", wordTime);
        resultMap.put("门店图标", icon);
        resultMap.put("门店地址", provinceCityDistrict);
        resultMap.put("门店具体地址", address);
        resultMap.put("门店描述", memo);
        String nullParam = Response.checkNull(resultMap);
        if (null != nullParam) {
            return Response.getError(nullParam + "不能为空");
        }
        try {
            Response response = appUserService.updateShopBusiness(shopId,shopName,shopPhone,wordTime,icon,provinceCityDistrict,address,memo);
            return response;
        } catch (ApplicationException ae) {
            logger.error(ae);
            ae.printStackTrace();
            return Response.getError(ae.errMsg);
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return Response.getError("服务器异常");
        }
    }

    @RequestMapping(value="/updateShopOperating")
    @ResponseBody
    public Response updateShopOperating(String shopId,String businessLicense,String licensePicurl,String principal,String principalPhone){
        logBefore(logger, "优惠券数据详情");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("商户编号", shopId);
        resultMap.put("营业执照号", businessLicense);
        resultMap.put("营业执照图", licensePicurl);
        resultMap.put("门店负责人", principal);
        resultMap.put("门店负责人手机号", principalPhone);
        String nullParam = Response.checkNull(resultMap);
        if (null != nullParam) {
            return Response.getError(nullParam + "不能为空");
        }
        try {
            Response response = appUserService.updateShopOperating(shopId,businessLicense,licensePicurl,principal,principalPhone);
            return response;
        } catch (ApplicationException ae) {
            logger.error(ae);
            ae.printStackTrace();
            return Response.getError(ae.errMsg);
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return Response.getError("服务器异常");
        }
    }




    /**
     * 修改登入密码
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/updatepassword", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Response updatePassword( String userId, String oldPassword, String newPassword) throws Exception {
        logBefore(logger, "密码修改");
        HashMap<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("用户编号", userId);
        resultMap.put("原密码", oldPassword);
        resultMap.put("新密码", newPassword);
        String nullParam=Response.checkNull(resultMap);
        if (null != nullParam) {
            return Response.getError(nullParam+"不能为空");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Response response = appUserService.updatepassword(userId,oldPassword,newPassword);
            return Response.getSuccess(map);
        } catch (ApplicationException ae) {
            logger.error(ae);
            return Response.getError(ae.getErrMsg());
        }
        catch (Exception e) {
            logger.error(e);
            return Response.getError("服务器异常");
        }
    }

    /**
     * 忘记登入密码
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/resetpassword", method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public Response resetpassword( String username, String phone, String password, String type, String code) throws Exception {
        logBefore(logger, "密码修改");
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HashMap<String, String> resultMap = new HashMap<String, String>();
            resultMap.put("登入账号", username);
            resultMap.put("新密码", password);
            resultMap.put("手机号码", phone);
            resultMap.put("短信验证码", code);
            String nullParam=Response.checkNull(resultMap);
            if (null != nullParam) {
                return Response.getError(nullParam+"不能为空");
            }
            RedisUtil redisUtil = new RedisUtil();
            Jedis jedis = redisUtil.getJedis();
            //String codemessage=(String) Const.CacheMapObject.get(Const.SESSION_PHONE_CODE+phone+type);
            String codemessage = jedis.get(Const.SESSION_PHONE_CODE+phone+type);
            logBefore(logger, "原验证码"+codemessage);
            if(Tools.isEmpty(codemessage)||!codemessage.equals(code)){
                return Response.getError("验证码输入错误");
            }
            Response response = appUserService.resetpassword(username,password,phone);
            //Const.CacheMapObject.remove(Const.SESSION_PHONE_CODE+phone+type);
            jedis.del(Const.SESSION_PHONE_CODE+phone+type);
            map.put("message", "处理成功");
            jedis.quit();
            return Response.getSuccess(map);
        } catch (ApplicationException ae) {
            logger.error(ae);
            return Response.getError(ae.getErrMsg());
        }
        catch (Exception e) {
            logger.error(e);
            return Response.getError("服务器异常");
        }
    }

























    /**
     * 退出登入
     *
     * @param shopId
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/outLogin", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Response outLogin(String shopId){
        logBefore(logger, "退出登入"+shopId);
        HashMap<String, String> resultMap = new HashMap<String, String>();
        resultMap.put("商户编号", shopId);
        String nullParam = Response.checkNull(resultMap);
        if (null != nullParam) {
            return Response.getError(nullParam + "不能为空");
        }
        try {
            tokenService.invalidate(shopId);
            return Response.getSuccess(null);
        }catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
            return Response.getError("服务器异常");
        }
    }

}
